package com.hmbe.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmbe.dto.Result;
import com.hmbe.entity.Shop;
import com.hmbe.mapper.ShopMapper;
import com.hmbe.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmbe.utils.RedisData;
import com.hmbe.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmbe.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryShopById(Long id) {
        //第一种:使用互斥锁解决缓存击穿问题的办法
        //return queryWithMutex(id);
        //第二种:使用逻辑过期解决缓存击穿问题的办法
        return queryWithLogicalExpire(id);
        /*//1.从redis中获取缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.判断是否有缓存
        if (shopJson != null) {
            //3.有缓存，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //4.没有缓存，查询数据库
        Shop shop = getById(id);
        //5.判断是否有数据
        if (shop != null) {
            //6.有数据，存入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return Result.ok(shop);
        }
        //7.没有数据，可能会出现缓存穿透，解决方案：缓存空值
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, null, CACHE_NULL_TTL, TimeUnit.MINUTES);

        //7.没有数据，返回错误
        return Result.fail("店铺不存在");*/

    }

    private Result queryWithLogicalExpire(Long id) {
        //1.从redis中获取缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.判断是否有缓存
        if (StrUtil.isBlank(shopJson)) {
            //3.没有缓存，查询数据库
            Shop shop = getById(id);
            //4.判断是否有数据
            if (shop != null) {
                //5.有数据，存入redis
                //5.1.设置逻辑过期
                RedisData redisData = new RedisData();
                redisData.setData(shop);
                //可以将过期时间设置成10秒,来测试逻辑过期
                redisData.setExpireTime(REDIS_LOGICAL_EXPIRE_TTL);
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
                return Result.ok(shop);
            }
        } else {
            //3.有缓存，判断是否过期
            RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
            if (redisData.getExpireTime() > System.currentTimeMillis()) {
                //3.1.未过期，直接返回
                Shop shop = JSONUtil.toBean(JSONUtil.toJsonStr(redisData.getData()), Shop.class);
                return Result.ok(shop);
            } else {
                //3.2.已过期，重构缓存,但是在重构的过程中，可能别的线程也在重构，所以需要加互斥锁
                return rebuildCache(id, redisData);

            }
        }
        return Result.fail("店铺不存在");
    }

    //创建一个固定大小的线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Result rebuildCache(Long id, RedisData redisData) {
        //3.2.1.获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        //3.2.2.判断是否获取成功
        if (Boolean.TRUE.equals(isLock)) {
            //使用线程池重构缓存，防止阻塞其他线程
            CACHE_REBUILD_EXECUTOR.execute(() -> {
                try {
                    //3.2.3.获取互斥锁成功，查询数据库
                    Shop shop = getById(id);
                    //3.2.4.判断是否有数据
                    if (shop != null) {
                        //3.2.5.有数据，更新缓存
                        redisData.setData(shop);
                        redisData.setExpireTime(System.currentTimeMillis() + REDIS_LOGICAL_EXPIRE_TTL);
                        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //3.2.6.释放互斥锁
                    stringRedisTemplate.delete(lockKey);
                }
            });
        }
        //3.2.3.获取互斥锁失败，直接返回旧的缓存数据
        return Result.ok(JSONUtil.toBean(JSONUtil.toJsonStr(redisData.getData()), Shop.class));


    }


    private Result queryWithMutex(Long id) {
        //1.从redis中获取缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.判断是否有缓存
        if (shopJson != null) {
            //3.有缓存，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //3.没有缓存，为了防止缓存击穿，加互斥锁
        //3.1.获取互斥锁
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_SHOP_KEY + id, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        //3.2.判断是否获取成功
        if (lock) {
            //3.3.获取互斥锁成功，查询数据库重建缓存
            Shop shop = getById(id);
            //3.4.判断是否有数据
            if (shop != null) {
                //3.5.有数据，存入redis
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
                return Result.ok(shop);
            }
            //3.6.没有数据，存入空值
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, null, CACHE_NULL_TTL, TimeUnit.MINUTES);
        } else {
            //3.3.获取互斥锁失败，休眠100ms，重新获取
            try {
                Thread.sleep(100);
                //
                queryWithMutex(id);
                return queryWithMutex(id);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //3.4.释放互斥锁
                stringRedisTemplate.delete(LOCK_SHOP_KEY + id);
            }
        }
        return Result.fail("店铺不存在");
    }

    @Override
    @Transactional
    public Result updateShopById(Shop shop) {
        //1.修改数据库
        Long id = shop.getId();
        //2.判断id是否存在
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //3.执行修改
        updateById(shop);
        //4.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }
}
